"""
    模拟手柄输入(pip3 install pygame)
    描述：使用Python和Pygame库控制Logitech Wireless Gamepad F710游戏手柄（pygame不支持断开重连检测）
"""
import pygame
import time

# 初始化pygame和手柄模块
pygame.init()
pygame.joystick.init()

# 检查是否有手柄连接
if pygame.joystick.get_count() == 0:
    print("未检测到游戏手柄！")
    exit()

# 初始化第一个手柄
joystick = pygame.joystick.Joystick(0)
joystick.init()

print(f"手柄名称: {joystick.get_name()}")
print(f"轴数量: {joystick.get_numaxes()}")
print(f"按钮数量: {joystick.get_numbuttons()}")
print(f"帽子开关数量: {joystick.get_numhats()}")
print("-" * 50)

# 定义死区阈值来减少轴的微小抖动
DEAD_ZONE = 0.1

def apply_dead_zone(value):
    """应用死区过滤来消除轴的微小抖动"""
    return value if abs(value) > DEAD_ZONE else 0.0

try:
    while True:
        # 处理事件（必须调用，否则无法获取最新状态）
        pygame.event.pump()

        # 读取所有摇杆轴的值并应用死区过滤
        num_axes = joystick.get_numaxes()
        axes = []
        for i in range(num_axes):
            raw_value = joystick.get_axis(i)
            filtered_value = apply_dead_zone(raw_value)
            axes.append(filtered_value)
        
        # 读取所有按钮状态
        buttons = [joystick.get_button(i) for i in range(joystick.get_numbuttons())]
        
        # 读取所有帽子开关状态
        hats = [joystick.get_hat(i) for i in range(joystick.get_numhats())]

        # 清屏效果
        print("\033[H\033[J")
        
        print("手柄输入数据:")
        print("=" * 50)
        
        # 打印摇杆轴数据（修正显示格式）
        axis_names = ["左摇杆X", "左摇杆Y", "LT", "右摇杆X", "右摇杆Y", "RT"]
        for i, axis in enumerate(axes):
            name = axis_names[i] if i < len(axis_names) else f"轴 {i}"
            print(f"{name:8}: {axis:>7.2f}")
        
        print("\n按钮状态:")
        button_names = ["A", "B", "X", "Y", "LB", "RB", "BACK", "START", "LS", "RS"]
        # 每行显示5个按钮
        for i in range(0, len(buttons), 5):
            line_items = []
            for j in range(5):
                if i + j < len(buttons):
                    name = button_names[i + j] if i + j < len(button_names) else f"B{i+j}"
                    status = "按下" if buttons[i + j] else "释放"
                    line_items.append(f"{name:6}: {status}")
            print("  " + "  ".join(line_items))
        
        print("\n帽子开关:")
        for i, hat in enumerate(hats):
            print(f"帽子 {i}   : X={hat[0]}, Y={hat[1]}")
        
        print("\n按 Ctrl+C 退出")
        time.sleep(0.1)

except KeyboardInterrupt:
    print("\n程序退出")
finally:
    pygame.quit()